package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.dto.WxLoginResponDTO;
import com.sky.entity.User;
import com.sky.enumeration.OpenIdType;
import com.sky.exception.WxLoginOpenIdException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Log4j2
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;


    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    WeChatProperties weChatProperties;
    public final String getOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public UserLoginVO wxlogin(UserLoginDTO userLoginDTO) {
        StringBuilder url = new StringBuilder();
        url.append(getOpenIdUrl)
                .append("?appid=")
                        .append(weChatProperties.getAppid())
                                .append("&secret=")
                                        .append(weChatProperties.getSecret())
                                                .append("&js_code=")
                                                        .append(userLoginDTO.getCode())
                                                                .append("&grant_type=authorization_code");

        log.info("访问地址：" + url);
        WxLoginResponDTO wxLoginResponDTO = JSONObject.parseObject(HttpClientUtil.doGet(url.toString(), null), WxLoginResponDTO.class);

        if(wxLoginResponDTO != null){

            for (OpenIdType openIdType : OpenIdType.values()) {
                if(wxLoginResponDTO.getOpenid().equals(openIdType.getCode())){
                    throw new WxLoginOpenIdException(openIdType.getMsg());
                }
            }

            if(wxLoginResponDTO.getOpenid().isEmpty()) throw new WxLoginOpenIdException("获取OpenId错误");
        }


        User user = userMapper.findUserByOpenId(wxLoginResponDTO.getOpenid());
        if(user == null){
            user = new User();
            user.setOpenid(wxLoginResponDTO.getOpenid());
            user.setCreateTime(LocalDateTime.now());
            userMapper.insertUserInfo(user);
        }

        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        return new UserLoginVO(user.getId(), user.getOpenid(), token);
    }
}
